package com.micro.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class ProcessUtil {
    /**
     * 创建命令执行器
     */
    private static final ProcessBuilder processBuilder = new ProcessBuilder();

    public static String executeCommand(boolean isError, List<String> commands) throws IOException {
        return executeCommandStr(String.join(",",commands),",");
    }
    public static String executeCommandStr(String command, String separator) throws IOException {
        return executeCommand(command != null ? command.split(StringUtils.isNotEmpty(separator) ? separator : " ") : new String[0]);
    }

    public static String executeCommand(String... commands) throws IOException {
        if(commands==null || commands.length==0){
            throw new RuntimeException("命令不能为空");
        }
        processBuilder.command().addAll(Arrays.asList(commands));
        Process process = processBuilder.start();
        log.info("执行命令位置：{}",process);
        InputStream inputStream = process.getInputStream();
        byte[] bytes = getBytes(inputStream);
        String result = new String(bytes, StandardCharsets.UTF_8);
        if(StringUtils.isBlank(result)){
            InputStream errorStream = process.getErrorStream();
            result = new String(getBytes(errorStream),"GBK");
        }
        return result;
    }

    @NotNull
    private static byte[] getBytes(InputStream inputStream) throws IOException {
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        return bytes;
    }
}
